package org.springblade.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.MsgTypeEnum;
import org.springblade.modules.admin.mapper.LiftElevatorMapper;
import org.springblade.modules.admin.mapper.PlanHistoryImageMapper;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.utils.WatermarkImgUtils;
import org.springblade.modules.admin.vo.SimpleElevatorInfoVO;
import org.springblade.modules.admin.vo.image.by.ByPlanHistoryImgVO;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@AllArgsConstructor
@Service
public class PlanHistoryImageServiceImpl extends BaseServiceImpl<PlanHistoryImageMapper, PlanHistoryImage> implements PlanHistoryImageService {

	private final IUserService userService;
	private final ITenantService tenantService;
	private final MaintainMsgService msgService;
	private final IMaintainPlanContentExtService planContentExtService;
	private final MaintainTemplateContentService templateContentService;
	private final ElevatorService elevatorService;

	@Override
	public Boolean saveAllImage(List<PlanHistoryImage> entityList) {
		entityList = entityList.stream().filter(e -> StringUtil.isNotBlank(e.getUrl())).collect(Collectors.toList());
		if(Func.isEmpty(entityList)){
			return Boolean.TRUE;
		}
		return super.saveBatch(entityList);
	}

	@Override
	public IPage<PlanHistoryImage> selectPage(IPage<PlanHistoryImage> page, PlanHistoryImage entity) {
		List<PlanHistoryImage> resultPage = baseMapper.selectPlanHistoryImagePage(page,entity);
		if(Func.isNotEmpty(resultPage)){
			List<User> userList = userService.list();
			List<Long> planIds = resultPage.stream().map(PlanHistoryImage::getPlanId).distinct().collect(Collectors.toList());
			List<MaintainPlanContentExt> planContentExts = new ArrayList<>();
			if(Func.isNotEmpty(planIds)){
				planContentExts = planContentExtService.list(Wrappers.<MaintainPlanContentExt>lambdaQuery().in(MaintainPlanContentExt::getPlanId,planIds));
			}
			List<Long> templateContentIds = resultPage.stream().map(PlanHistoryImage::getTemplateContentId).distinct().collect(Collectors.toList());
			List<MaintainTemplateContent> templateContents = new ArrayList<>();
			if(Func.isNotEmpty(templateContentIds)){
				templateContents = templateContentService.list(Wrappers.<MaintainTemplateContent>lambdaQuery().in(MaintainTemplateContent::getId,templateContentIds));
			}
			List<Long> elevatorIds = resultPage.stream().map(PlanHistoryImage::getElevatorId).distinct().collect(Collectors.toList());
			List<SimpleElevatorInfoVO> elevatorInfoList = new ArrayList<>();
			if(Func.isNotEmpty(elevatorIds)){
				elevatorInfoList = elevatorService.listSimpleElevatorInfoByIds(elevatorIds);
			}
			List<MaintainPlanContentExt> finalPlanContentExts = planContentExts;
			List<MaintainTemplateContent> finalTemplateContents = templateContents;
			List<SimpleElevatorInfoVO> finalElevatorInfoList = elevatorInfoList;
			resultPage.forEach(e -> {
				if(Func.isNotEmpty(e.getUpdateUser())){
					User user = userList.stream().filter(t -> t.getId().equals(e.getUpdateUser())).findFirst().orElse(new User());
					e.setUpdateUserName(user.getRealName());
				}
				if(Func.isNotEmpty(e.getAppealUser())){
					User user = userList.stream().filter(t -> t.getId().equals(e.getAppealUser())).findFirst().orElse(new User());
					e.setAppealUserName(user.getRealName());
				}
				if(Func.isNotEmpty(e.getPlanId()) && Func.isNotEmpty(finalPlanContentExts)){
					MaintainPlanContentExt ext = finalPlanContentExts.stream().filter(t -> t.getPlanId().equals(e.getPlanId())).findFirst().orElse(new MaintainPlanContentExt());
					e.setScoreSpotCheckType(String.valueOf(ext.getScoreSpotCheckType()));
				}
				if(Func.isNotEmpty(e.getTemplateContentId()) && Func.isNotEmpty(finalTemplateContents)){
					MaintainTemplateContent templateContent = finalTemplateContents.stream().filter(t -> t.getId().equals(e.getTemplateContentId())).findFirst().orElse(new MaintainTemplateContent());
					e.setPartScore(templateContent.getPartScore());
				}
				if(Func.isNotEmpty(e.getElevatorId()) && Func.isNotEmpty(finalElevatorInfoList)){
					SimpleElevatorInfoVO elevatorInfo = finalElevatorInfoList.stream().filter(t -> t.getElevatorId().equals(e.getElevatorId())).findFirst().orElse(new SimpleElevatorInfoVO());
					e.setElevatorAddress(elevatorInfo.getElevatorAddress());
					e.setBuildingName(elevatorInfo.getBuildingName());
				}
			});
		}
		return page.setRecords(resultPage);
	}

	@Override
	public List<PlanHistoryImage> selectList(PlanHistoryImage entity) {
		return baseMapper.selectImageList(entity);
	}

	@Override
	public PlanHistoryImage selectDetail(Long id, String url) {
		return baseMapper.selectDetail(id,url);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void countPlanHistoryImageStatus() {
		List<User> userList = userService.getUserListOfRoleCode("approveRole,worksScore,aiList",null);
		if(Func.isNotEmpty(userList)){
			PlanHistoryImage entity = new PlanHistoryImage();
			entity.setResultStr("1,2");
			entity.setStatusStr("1");
			List<PlanHistoryImage> planHistoryImages = baseMapper.selectImageList(entity);
			Map<String,List<User>> tenantGroup = userList.stream().collect(Collectors.groupingBy(User::getTenantId));
			tenantGroup.forEach((k,v) -> {
				long count = planHistoryImages.stream().filter(t -> t.getTenantId().equals(k) && "3,4,5".contains(String.valueOf(t.getPlanStatus()))).count();
				if(count > 0){
					MaintainMsg maintainMsg = new MaintainMsg();
					maintainMsg.setTitle("AI结果人工审核提醒");
					maintainMsg.setContent("存在" + count + "条「待办审核」AI识别数据，请及时处理。");
					maintainMsg.setType(MsgTypeEnum.PLAN_HISTORY_IMAGE.getId());
					maintainMsg.setTenantId(k);
					msgService.sendMsg(maintainMsg, v.stream().map(User::getId).distinct().collect(Collectors.toList()),k);
				}
			});
		}
	}

	@Override
	public List<PlanHistoryImage> selectListAi(String startDate, String endDate) {
		return baseMapper.selectListAi(startDate,endDate);
	}

	@Override
	public List<ByPlanHistoryImgVO> selectByHistoryImgList(String startDate, String endDate) {
		List<ByPlanHistoryImgVO> resultList = new ArrayList<>();
		List<ByPlanHistoryImgVO> imgVOS = baseMapper.selectByHistoryImgList(startDate,endDate);
		if (Func.isNotEmpty(imgVOS)){
			imgVOS.forEach(e -> {
				List<String> imgList = new ArrayList<>();
				if(Func.isNotEmpty(e.getRecordData())){
					imgList.addAll(WatermarkImgUtils.findImgVideoUrl(e.getRecordData().toString()));
				}
				if(Func.isNotEmpty(e.getCheckRecords())){
					Map<Long,List<MaintainCheckRecord>> userGroup = e.getCheckRecords().stream().collect(Collectors.groupingBy(MaintainCheckRecord::getUserId));
					userGroup.forEach((k,v) -> {
						List<MaintainCheckRecord> userRecords = v.stream().sorted(Comparator.comparing(MaintainCheckRecord::getUpdateTime).reversed()).collect(Collectors.toList());
						MaintainCheckRecord userRecord = userRecords.get(0);
						if(Func.isNotEmpty(userRecord.getRecordDataValue())){
							imgList.addAll(WatermarkImgUtils.findImgVideoUrl(userRecord.getRecordDataValue().toString()));
						}
					});
				}
				if(Func.isNotEmpty(imgList)){
					imgList.forEach(t -> {
						ByPlanHistoryImgVO result = new ByPlanHistoryImgVO();
						result.setBuildingName(e.getBuildingName());
						result.setElevatorAddress(e.getElevatorAddress());
						result.setProvinceName(e.getProvinceName());
						result.setCityName(e.getCityName());
						result.setAdName(e.getAdName());
						result.setPlanId(e.getPlanId());
						result.setTemplateContentId(e.getTemplateContentId());
						result.setTemplateContentName(e.getTemplateContentName());
						result.setPlanDate(e.getPlanDate());
						result.setBuildingTypeName(e.getBuildingTypeName());
						result.setImgUrl(t);
						result.setPlanQuestionDesc(e.getPlanQuestionDesc());
						result.setPlanScoreFutilityDesc(e.getPlanScoreFutilityDesc());
						result.setBrandName(e.getBrandName());
						result.setBrandVersionName(e.getBrandVersionName());
						resultList.add(result);
					});
				}
			});
		}
		return resultList;
	}

	@Override
	public List<ByPlanHistoryImgVO> selectBySignHistoryImgList(String startDate, String endDate) {
		return baseMapper.selectBySignHistoryImgList(startDate,endDate);
	}

	@Override
	public List<ByPlanHistoryImgVO> selectCallBackImgList(String startDate, String endDate) {
		return baseMapper.selectCallBackImgList(startDate,endDate);
	}

	@Override
	public Integer selectPageCount(PlanHistoryImage entity) {
		return baseMapper.selectPageCount(entity);
	}
}
